<?php

namespace Wechat\Controller;

use Think\Controller;
use Com\Wechat;
use Com\WechatAuth;
use Com\JSSDK;
use Think\Model;

class ShopController extends Controller
{
    protected $msg = array('code' => 0, 'msg' => '', 'data' => array());
    protected $_code = 0;
    protected $_msg = '';
    protected $_data = '';

    public function _initialize()
    {
        header("Content-Type:text/html; charset=utf-8");
        session('member', array('member_id' => 2120, 'openid' => 'o2uRPs44YHtX4NqbqicggQZdRC8g', 'nickname' => '鱼消失了'));
    }

    protected function outputMsg()
    {
        $msg['code'] = $this->_code;
        $msg['msg'] = $this->_msg;
        if (!empty($this->_data)) {
            $msg['data'] = $this->_data;
        }
        $this->ajaxReturn($msg);
    }

    public function index()
    {
        $member = session('member');
        if (empty($member)) {
            $auth = new WechatAuth(C('WECHAT_APPID'), C('WECHAT_APPSECRET'));
            if (!isset($_GET['code'])) {
                $baseUrl = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . $_SERVER['QUERY_STRING'];
                $url = $auth->getRequestCodeURL($baseUrl, 'shop', 'snsapi_userinfo');
                Header("Location: {$url}");
                exit();
            } else {
                $token = $auth->getAccessToken('code', $_GET['code']);
            }
            $userInfo = $auth->getUserInfo($token['openid']);
            $member = getMember($token['openid'], false);

            if (empty($member)) {
                $member = array();
                $member['nickname'] = isset($userInfo['nickname']) ? $userInfo['nickname'] : '';
                $member['gender'] = isset($userInfo['sex']) ? $userInfo['sex'] : 0;
                $member['avatar'] = isset($userInfo['headimgurl']) ? $userInfo['headimgurl'] : '';
                $member['openid'] = $userInfo['openid'];
                $member['status'] = 1;
                $member['vip_start_time'] = '0000-00-00';
                $member['vip_end_time'] = '0000-00-00';
                $member['subscribe_time'] = 0;
                $member['create_time'] = NOW_TIME;
                $member['member_id'] = D('Member')->update($member);
                if (!$member['member_id']) {
                    exit('获取用户信息失败，请稍后重试');
                }
            } else {
                D('Member')->updateMember($member['member_id'], $userInfo['nickname'], $userInfo['sex'], $userInfo['headimgurl']);
            }

        } else {
            $member = getMember($member['openid'], false);
        }

        if (empty($member)) {
            exit('获取用户信息失败，请稍后重试');
        }

        session('member', array('member_id' => $member['member_id'], 'openid' => $member['openid'], 'nickname' => $member['nickname']));
        $this->display();
    }

    public function confirmOrder()
    {
        $this->display('confirmOrder');
    }

    public function getRegionList()
    {
        $keyword = I('get.keyword');
        $where = array();
        if ($keyword) {
            $where['region_name'] = array('like', "%{$keyword}%");
            $where['status'] = 1;
            $list = M('Region')->field('region_id,region_name')->where($where)->order('click DESC')->limit(10)->select();
        } else {
            $list = array();
        }

        $this->_code = 0;
        $this->_msg = 'ok';
        $this->_data = $list;
        $this->outputMsg();
    }

    public function getData()
    {
        $member = session('member');
        if (empty($member)) {
            $this->_code = 10402;
            $this->_msg = '获取用户信息失败，请稍后重试';
            $this->outputMsg();
        }

        $memberAddress = M('MemberAddress')->where(array('member_id' => $member['member_id'], 'status' => 1))->find();
        if (!empty($memberAddress['region_id'])) {
            $regionList = getRegion();
            if (empty($regionList[$memberAddress['region_id']])) {
                $result = M('Region')->where('status = 1')->order('click DESC, region_id DESC')->find();
                $region = ['region_id' => $result['region_id'], 'region_name' => $result['region_name'], 'first' => 1];
                $member['first'] = 1;
                session('member', $member);
            } else {
                $region = ['region_id' => $memberAddress['region_id'], 'region_name' => $memberAddress['region_name'], 'first' => 0];
            }
        } else {
            $result = M('Region')->where('status = 1')->order('click DESC, region_id DESC')->find();
            $region = ['region_id' => $result['region_id'], 'region_name' => $result['region_name'], 'first' => 1];
            $member['first'] = 1;
            session('member', $member);
        }

        $date = array();
        $dateList = getMenuDate($region['region_id']);
        if (empty($dateList)) {
            $this->_code = 10999;
            $this->_msg = '该楼宇没有菜品售卖';
            $this->outputMsg();
        }

        $cate = getGoodsCategory();
        foreach ($dateList as $menuKey => $menu) {
            $current = array();
            $current['menu_date'] = date('m月d日', $menu['menu_date']);
            $current['menu_week'] = getWeek($menu['menu_date']);
            $current['token'] = encrypt($menu['menu_id']);
            $current['menu_time'] = $menu['menu_date'];
            $remind = array();
            $goods = array();
            $orderGoods = D('OrderGoods')->getMemberOrderGoods($member['member_id'], $menu['menu_id']);
            if ($orderGoods) {
                $order = array();
                foreach ($orderGoods as $val) {
                    $order[] = $val['goods_name'] . 'x' . $val['goods_num'];
                }
                $current['order'] = $order;
            } else {
                $current['order'] = array();
            }

            $overTime = strtotime(date('Y-m-d ' . getConfig('order_time', false), $menu['menu_date']));
            // 已截止
            if (time() > $overTime) {
                $current['menu_title'] = '已截止';
                $remind['title'] = '当日已全部售罄';
                $week = getWeek($dateList[1]['menu_date']);
                $remind['desc'] = "点击提前预定{$week}餐品";

                $menuGoods = D('MenuGoods')->getMenuGoods($menu['menu_id']);
                if ($menuGoods) {
                    foreach ($menuGoods as $val) {
                        $tmp = array();
                        $tmp['goods_id'] = $val['goods_id'];
                        $tmp['cate_id'] = $val['cate_id'];
                        $tmp['cate_title'] = $cate[$val['cate_id']];
                        $tmp['goods_name'] = $val['goods_name'];
                        $tmp['goods_image'] = $val['goods_image'];
                        $tmp['goods_combo'] = $val['goods_combo'];
                        $tmp['market_price'] = $val['market_price'];
                        $tmp['shop_price'] = $val['shop_price'];
                        $tmp['store_id'] = $val['store_id'];
                        $store = getStore($val['store_id']);
                        $tmp['store_logo'] = $store['store_logo'];
                        $tmp['store_slogan'] = $store['store_slogan'];
                        $tmp['goods_storage'] = 0;
                        $goods[] = $tmp;
                    }
                }
            } else {
                // 未截止
                $menuGoods = D('MenuGoods')->getMenuGoods($menu['menu_id']);
                $allStoreage = 0;
                if ($menuGoods) {
                    foreach ($menuGoods as $val) {
                        $tmp = array();
                        $tmp['goods_id'] = $val['goods_id'];
                        $tmp['cate_id'] = $val['cate_id'];
                        $tmp['cate_title'] = $cate[$val['cate_id']];
                        $tmp['goods_name'] = $val['goods_name'];
                        $tmp['goods_image'] = $val['goods_image'];
                        $tmp['goods_combo'] = $val['goods_combo'];
                        $tmp['market_price'] = $val['market_price'];
                        $tmp['shop_price'] = $val['shop_price'];
                        $tmp['store_id'] = $val['store_id'];
                        $store = getStore($val['store_id']);
                        $tmp['store_logo'] = $store['store_logo'];
                        $tmp['store_slogan'] = $store['store_slogan'];

                        $key = C('CACHE_KEY_MENU_GOODS_SELL_NUM') . $val['menu_id'] . '_' . $val['goods_id'];
                        $sellNum = S($key);

                        $surplus = $val['goods_storage'] - $sellNum;
                        $surplus = $surplus <= 0 ? 0 : $surplus;

                        $tmp['goods_storage'] = $surplus;
                        $allStoreage += $surplus;
                        $goods[] = $tmp;
                    }
                    if ($allStoreage <= 0) {
                        $current['menu_title'] = '已售罄';
                        $remind['title'] = '当日已全部售罄';
                        $week = getNextWeek($current['menu_week']);
                        $remind['desc'] = "点击提前预定{$week}餐品";
                    } else {
                        if ($menuKey == 0) {
                            $current['menu_title'] = '';
                            $remind['title'] = '距今日订餐结束';
                            $remind['time'] = $overTime;
                            $week = getWeek($dateList[1]['menu_date']);
                            $remind['desc'] = "点击提前预定{$week}餐品";
                        }
                    }
                } else {
                    $current['menu_title'] = '已售罄';
                    $remind['title'] = '当日已全部售罄';
                    $week = getNextWeek($current['menu_week']);
                    $remind['desc'] = "点击提前预定{$week}餐品";
                }
            }
            $current['goods'] = $goods;
            $current['remind'] = $remind;
            $date[] = $current;
        }

        $comment = D('OrderGoods')->getCommentGoods($member['member_id']);
        $commentID = !empty($comment) ? $comment['id'] : 0;
        $this->_code = 0;
        $this->_msg = 'ok';
        $this->_data = ['region' => $region, 'menu' => $date, 'comment' => $commentID, 'first' => $region['first']];
        $this->outputMsg();
    }

    public function getCurrentData()
    {
        $regionId = I('post.region_id');
        $menuDate = I('post.menu_date');
        $menuKey = I('post.menu_key');

        if (empty($regionId)) {
            $this->_code = 10501;
            $this->_msg = '无效的楼宇地区，请重新选择';
            $this->outputMsg();
        }
        if (empty($menuDate)) {
            $this->_code = 10502;
            $this->_msg = '菜单日期不正确';
            $this->outputMsg();
        }

        $member = session('member');
        if (empty($member)) {
            $this->_code = 10402;
            $this->_msg = '获取用户信息失败，请稍后重试';
            $this->outputMsg();
        }

        $menu = getTodayMenu($regionId, $menuDate);
        if (empty($menu)) {
            $this->_code = 10503;
            $this->_msg = '该楼宇没有餐品售卖';
            $this->outputMsg();
        }

        $memberAddress = M('MemberAddress')->where(array('member_id' => $member['member_id'], 'status' => 1))->find();
        $region = getRegion();
        if (empty($memberAddress)) {
            $address = array();
            $address['member_id'] = $member['member_id'];
            $address['member_name'] = $member['nickname'];
            $address['member_phone'] = '';
            $address['region_id'] = $regionId;
            $address['region_name'] = $region[$regionId];
            $address['address'] = '';
            $address['status'] = 1;
            $address['is_default'] = 1;
            $address['create_time'] = time();
            M('MemberAddress')->add($address);
        } else {
            M('MemberAddress')->where(array('member_id' => $member['member_id']))->save(array('region_id' => $regionId, 'region_name' => $region[$regionId]));
        }

        $current = array();
        $current['menu_date'] = date('m月d日', $menuDate);
        $current['menu_week'] = getWeek($menuDate);
        $current['token'] = encrypt($menu['menu_id']);
        $current['menu_time'] = $menu['menu_date'];
        $remind = array();
        $goods = array();
        $orderGoods = D('OrderGoods')->getMemberOrderGoods($member['member_id'], $menu['menu_id']);
        if ($orderGoods) {
            $order = array();
            foreach ($orderGoods as $val) {
                $order[] = $val['goods_name'] . 'x' . $val['goods_num'];
            }
            $current['order'] = $order;
        } else {
            $current['order'] = array();
        }
        $cate = getGoodsCategory();
        $overTime = strtotime(date('Y-m-d ' . getConfig('order_time', false), $menu['menu_date']));
        // 已截止
        if (time() > $overTime) {
            $current['menu_title'] = '已截止';
            $remind['title'] = '当日已全部售罄';
            $week = getNextWeek($current['menu_week']);
            $remind['desc'] = "点击提前预定{$week}餐品";

            $menuGoods = D('MenuGoods')->getMenuGoods($menu['menu_id']);
            if ($menuGoods) {
                foreach ($menuGoods as $val) {
                    $tmp = array();
                    $tmp['goods_id'] = $val['goods_id'];
                    $tmp['cate_id'] = $val['cate_id'];
                    $tmp['cate_title'] = $cate[$val['cate_id']];
                    $tmp['goods_name'] = $val['goods_name'];
                    $tmp['goods_image'] = $val['goods_image'];
                    $tmp['goods_combo'] = $val['goods_combo'];
                    $tmp['market_price'] = $val['market_price'];
                    $tmp['shop_price'] = $val['shop_price'];
                    $tmp['store_id'] = $val['store_id'];
                    $store = getStore($val['store_id']);
                    $tmp['store_logo'] = $store['store_logo'];
                    $tmp['store_slogan'] = $store['store_slogan'];
                    $tmp['goods_storage'] = 0;
                    $goods[] = $tmp;
                }
            }
        } else {
            // 未截止
            $menuGoods = D('MenuGoods')->getMenuGoods($menu['menu_id']);
            $allStoreage = 0;
            if ($menuGoods) {
                foreach ($menuGoods as $val) {
                    $tmp = array();
                    $tmp['goods_id'] = $val['goods_id'];
                    $tmp['cate_id'] = $val['cate_id'];
                    $tmp['cate_title'] = $cate[$val['cate_id']];
                    $tmp['goods_name'] = $val['goods_name'];
                    $tmp['goods_image'] = $val['goods_image'];
                    $tmp['goods_combo'] = $val['goods_combo'];
                    $tmp['market_price'] = $val['market_price'];
                    $tmp['shop_price'] = $val['shop_price'];
                    $tmp['store_id'] = $val['store_id'];
                    $store = getStore($val['store_id']);
                    $tmp['store_logo'] = $store['store_logo'];
                    $tmp['store_slogan'] = $store['store_slogan'];

                    $key = C('CACHE_KEY_MENU_GOODS_SELL_NUM') . $val['menu_id'] . '_' . $val['goods_id'];
                    $sellNum = S($key);

                    $surplus = $val['goods_storage'] - $sellNum;
                    $surplus = $surplus <= 0 ? 0 : $surplus;

                    $tmp['goods_storage'] = $surplus;
                    $allStoreage += $surplus;
                    $goods[] = $tmp;
                }
                if ($allStoreage <= 0) {
                    $current['menu_title'] = '已售罄';
                    $remind['title'] = '当日已全部售罄';
                    $week = getNextWeek($current['menu_week']);
                    $remind['desc'] = "点击提前预定{$week}餐品";
                } else {
                    if ($menuKey == 0) {
                        $current['menu_title'] = '';
                        $remind['title'] = '距今日订餐结束';
                        $remind['time'] = $overTime;
                        $week = getNextWeek($current['menu_week']);
                        $remind['desc'] = "点击提前预定{$week}餐品";
                    }
                }
            } else {
                $current['menu_title'] = '已售罄';
                $remind['title'] = '当日已全部售罄';
                $remind['desc'] = "点击提前预定餐品";
            }
        }

        $current['goods'] = $goods;
        $current['remind'] = $remind;
        $current['first'] = 1;

        $this->_code = 0;
        $this->_msg = 'ok';
        $this->_data = $current;
        $this->outputMsg();
    }


    public function submitCart()
    {
        $cart = I('post.cart');
//        $cart = json_decode($cart, true);
//        $goods1[] = ['goods_id' => 37, 'goods_num' => 2];
//        $goods1[] = ['goods_id' => 44, 'goods_num' => 1];
//        $goods2[] = ['goods_id' => 30, 'goods_num' => 1];
//        $cart = [
//            'region' => ['region_id' => 455, 'region_name' => '百富国际大厦'],
//            'data' => [
//                ['menu_date' => '12月05日', 'menu_week' => '周一', 'token' => "MDAwMDAwMDAwMIOtm5Y", 'goods' => $goods1],
//                ['menu_date' => '12月06日', 'menu_week' => '周二', 'token' => "MDAwMDAwMDAwMIOtm94", 'goods' => $goods2],
//            ]
//        ];

        if (empty($cart['region']['region_id'])) {
            $this->_code = 10101;
            $this->_msg = '无效的楼宇地区，请重新选择';
            $this->outputMsg();
        }

        if (empty($cart['data'])) {
            $this->_code = 10102;
            $this->_msg = '购物车是空的，请添加商品';
            $this->outputMsg();
        }

        $member = session('member');
        if (empty($member)) {
            $this->_code = 10402;
            $this->_msg = '获取用户信息失败，请稍后重试';
            $this->outputMsg();
        }

        $coupon = getOptimalCoupon($member['member_id']);

        $order = array();
        $order['region_id'] = $cart['region']['region_id'];
        $order['region_name'] = $cart['region']['region_name'];
        $order['coupon_id'] = isset($coupon['coupon_id']) ? $coupon['coupon_id'] : 0;
        $order['coupon_sn'] = isset($coupon['coupon_sn']) ? $coupon['coupon_sn'] : 0;
        $order['coupon_value'] = isset($coupon['coupon_value']) ? $coupon['coupon_value'] : 0;
        $menus = array();
        $goodsAmount = 0;
        $goodsCount = 0;
        $orderGoodsAmount = 0;
        $time = strtotime(date('Y-m-d 00:00:00'));
        $vDay = getConfig('discount_day');
        $discountTwo = [];
        foreach ($cart['data'] as $key => $value) {
            $menuId = intval(decrypt($value['token']));
            if ($menuId == 0 || empty($value['goods'])) {
                $this->_code = 10103;
                $this->_msg = '购物车异常，请重新提交购物';
                $this->outputMsg();
            }
            $mu = getMenu($menuId, false);
            if (empty($mu)) {
                $this->_code = 10103;
                $this->_msg = '购物车异常，请重新提交购物';
                $this->outputMsg();
            }

            if ($time > $mu['menu_date']) {
                $this->_code = 10106;
                $this->_msg = '菜单已经过期';
                $this->outputMsg();
            }
            $menu = array();
            $menu['menu_week'] = getWeek($mu['menu_date']);
            $menu['menu_date'] = date("m月d日", $mu['menu_date']);
            $menu['menu_time'] = $mu['menu_date'];
            $menu['area_id'] = $mu['area_id'];
            $menu['menu_id'] = $menuId;
            $shopPrice = 0;
            $goodsPrice = 0;
            foreach ($value['goods'] as $cartGoods) {
                $goods = D('MenuGoods')->getMenuGoods($menuId, $cartGoods['goods_id']);
                if (empty($goods)) {
                    $this->_code = 10105;
                    $this->_msg = '购物车商品下架，请重新选择';
                    $this->outputMsg();
                } else {
                    $goods = $goods[0];
                    $key = C('CACHE_KEY_MENU_GOODS_SELL_NUM') . $menuId . '_' . $cartGoods['goods_id'];
                    $sellNum = S($key);
                    $surplus = $goods['goods_storage'] - $sellNum;
                    if ($surplus < $cartGoods['goods_num']) {
                        $this->_code = 10104;
                        $this->_msg = $goods['goods_name'] . ' 库存不足，请重新选择';
                        $this->outputMsg();
                    }
                    $goodsPrice += $goods['market_price'] * $cartGoods['goods_num'];
                    $shopPrice += $goods['shop_price'] * $cartGoods['goods_num'];
                    $goodsCount += $cartGoods['goods_num'];
                    $tGoods = [
                        'goods_id' => $goods['goods_id'],
                        'goods_name' => $goods['goods_name'],
                        'goods_num' => $cartGoods['goods_num'],
                        'market_price' => $goods['market_price'],
                        'shop_price' => $goods['shop_price'],
                    ];

                    if ((count($value['goods']) >= 2 || $cartGoods['goods_num'] >= 2) && $mu['menu_date'] == $vDay) {
                        if (!empty($discountTwo['goods_id'])) {
                            if ($discountTwo['shop_price'] < $goods['shop_price']) {
                                $discountTwo['goods_id'] = $goods['goods_id'];
                                $discountTwo['shop_price'] = $goods['shop_price'];
                                $discountTwo['goods_name'] = $goods['goods_name'];
                            }
                        } else {
                            $discountTwo['goods_id'] = $goods['goods_id'];
                            $discountTwo['shop_price'] = $goods['shop_price'];
                            $discountTwo['goods_name'] = $goods['goods_name'];
                        }
                    }
                    $menu['goods'][] = $tGoods;
                }
            }
            $orderGoodsAmount += $goodsPrice;
            $goodsAmount += $shopPrice;
            $menu['goods_price'] = $goodsPrice;
            $menu['goods_amount'] = $shopPrice;
            $menus[] = $menu;
        }

        if (!empty($discountTwo['goods_id'])) {
            $twoPrice = $discountTwo['shop_price'] / 2;
            $order['discount_two'] = ['goods_name' => $discountTwo['goods_name'], 'discount_price' => $twoPrice];
        } else {
            $order['discount_two'] = ['goods_name' => '', 'discount_price' => 0];
        }

        $deliverAmount = getConfig('deliver_amount');
        $dishwareAmount = getConfig('dishware_amount');
        $order['menu'] = $menus;
        $order['goods_price'] = $orderGoodsAmount;
        $order['goods_count'] = $goodsCount;
        $order['goods_amount'] = $goodsAmount;
        $order['discount_amount'] = ($orderGoodsAmount - $goodsAmount) + $order['coupon_value'] + $deliverAmount + $dishwareAmount;

        $order['deliver_time'] = '每天送餐时间' . getConfig('deliver_time');
        $order['deliver_amount'] = $deliverAmount; // 送餐
        $order['dishware_amount'] = $dishwareAmount; // 餐盒费
        $order['order_total'] = $orderGoodsAmount + $deliverAmount + $dishwareAmount;
        $orderAmount = $order['order_total'] - $order['discount_amount'] - $order['discount_two']['discount_price'];
        $order['order_amount'] = $orderAmount > 0 ? $orderAmount : 1;

        $memberAddress = M('MemberAddress')->where(array('member_id' => $member['member_id'], 'status' => 1))->find();
        $order['member_name'] = isset($memberAddress['member_name']) ? $memberAddress['member_name'] : '';
        $order['member_phone'] = isset($memberAddress['member_phone']) ? $memberAddress['member_phone'] : '';
        $order['address'] = isset($memberAddress['address']) ? $memberAddress['address'] : '';


        S(C('CACHE_KEY_MEMBER_ORDER') . $member['member_id'], $order, 86400);
        $this->_code = 0;
        $this->_msg = 'ok';
        $this->_data = $order;
        $this->outputMsg();

    }

    public function submitOrder()
    {
        $regionID = I('post.region_id');
        $reciverName = I('post.member_name');
        $reciverPhone = I('post.member_phone');
        $regionName = I('post.region_name');
        $address = I('post.address');

        if (empty($regionID)) {
            $this->_code = 10201;
            $this->_msg = '下单地址填写有误，请重新选择楼宇';
            $this->outputMsg();
        }
        if (empty($reciverName)) {
            $this->_code = 10202;
            $this->_msg = '请填写收货人姓名';
            $this->outputMsg();
        }
        if (empty($reciverPhone)) {
            $this->_code = 10203;
            $this->_msg = '请填写收货人电话';
            $this->outputMsg();
        }
        if (empty($address)) {
            $this->_code = 10204;
            $this->_msg = '请填写收货人地址';
            $this->outputMsg();
        }

        $member = session('member');
        if (empty($member)) {
            $this->_code = 10402;
            $this->_msg = '获取用户信息失败，请稍后重试';
            $this->outputMsg();
        }

        vendor('wxpay.WxPay#Api');
        vendor('wxpay.WxPay#JsApiPay');

        $tools = new \JsApiPay();
        $openId = $member['openid'];

        $cacheOrder = S(C('CACHE_KEY_MEMBER_ORDER') . $member['member_id']);
        if (empty($cacheOrder)) {
            $this->_code = 10205;
            $this->_msg = '订单超时，请重新选择菜品下单';
            $this->outputMsg();
        }

        $order = array();
        $order['order_sn'] = getOrderSN();
        $order['member_id'] = $member['member_id'];
        $order['goods_num'] = $cacheOrder['goods_count'];
        $order['goods_amount'] = $cacheOrder['goods_amount'];
        $order['order_amount'] = $cacheOrder['order_amount'];
        $order['discount_amount'] = $cacheOrder['discount_amount'];
        $order['pay_id'] = 1;
        $order['pay_code'] = 'wxpay';
        $order['pay_time'] = 0;
        $order['pay_amount'] = $cacheOrder['order_amount'];
        $order['order_state'] = 1;
        $order['coupon_id'] = $cacheOrder['coupon_id'];
        $order['coupon_sn'] = $cacheOrder['coupon_sn'];
        $order['create_time'] = NOW_TIME;
        $order['update_time'] = NOW_TIME;

        $input = new \WxPayUnifiedOrder();
        $input->SetBody($order['order_sn']); //描述
        $input->SetOut_trade_no($order['order_sn']);
//        $input->SetTotal_fee(1);
        $input->SetTotal_fee($order['pay_amount'] * 100); // 订单总金额，单位为分 不能有小数点。
        $input->SetTime_start(date('YmdHis'));
        $input->SetTime_expire(date('YmdHis', time() + 600));
        $input->SetNotify_url(C('SITE_URL') . 'wechat/notify/wxpay_notify');
        $input->SetTrade_type('JSAPI');
        $input->SetOpenid($openId);
        $payOrder = \WxPayApi::unifiedOrder($input, 30);

        $jsApiParameters = $tools->GetJsApiParameters($payOrder);
        $jsApiParameters = json_decode($jsApiParameters);

        if ($jsApiParameters) {
            $model = new Model();
            try {
                $model->startTrans();

                $addressData = array('region_id' => $regionID, 'region_name' => $regionName, 'member_name' => $reciverName, 'member_phone' => $reciverPhone, 'address' => $address);
                $model->table('__MEMBER_ADDRESS__')->where(array('member_id' => $member['member_id'], 'status' => 1))->save($addressData);

                $order['order_id'] = $model->table('__ORDER__')->add($order);
                $allGoods = array();
                foreach ($cacheOrder['menu'] as $menu) {
                    foreach ($menu['goods'] as $val) {
                        $goods = getGoods($val['goods_id']);
                        $og = array();
                        $og['order_id'] = $order['order_id'];
                        $og['order_sn'] = $order['order_sn'];
                        $og['menu_id'] = $menu['menu_id'];
                        $og['menu_date'] = $menu['menu_time'];
                        $og['area_id'] = $menu['area_id'];
                        $og['store_id'] = $goods['store_id'];
                        $og['member_id'] = $member['member_id'];
                        $og['goods_id'] = $goods['goods_id'];
                        $og['goods_sn'] = $goods['goods_sn'];
                        $og['goods_name'] = $goods['goods_name'];
                        $og['goods_price'] = $goods['market_price'];
                        $og['goods_num'] = $val['goods_num'];
                        $og['goods_image'] = $goods['goods_image'];
                        $og['goods_pay_price'] = $goods['shop_price'];
                        $og['create_time'] = NOW_TIME;
                        $allGoods[] = $og;
                    }
                }
                $model->table('__ORDER_GOODS__')->addAll($allGoods);

                $common = array();
                $common['order_id'] = $order['order_id'];
                $common['order_sn'] = $order['order_sn'];
                $common['member_id'] = $order['member_id'];
                $common['region_id'] = $regionID;
                $common['region_name'] = $regionName;
                $common['address'] = $address;
                $common['reciver_name'] = $reciverName;
                $common['reciver_phone'] = $reciverPhone;
                $common['deliver_address'] = '';
                $common['create_time'] = NOW_TIME;
                $common['update_time'] = NOW_TIME;
                $model->table('__ORDER_COMMON__')->add($common);

                $model->commit();

                $this->_code = 0;
                $this->_msg = 'ok';
                $this->_data = $jsApiParameters;
                $this->outputMsg();
            } catch (\Exception $e) {
                dump($e);
                $model->rollback();
                $this->_code = 10210;
                $this->_msg = '下单失败，请重新购买下单';
                $this->outputMsg();
            }
        } else {
            $this->_code = 10210;
            $this->_msg = '下单失败，请重新购买下单';
            $this->outputMsg();
        }
    }

    public function getComment()
    {
        $commentId = I('post.comment_id');
        if (empty($commentId)) {
            $this->_code = 10300;
            $this->_msg = '请指定评价的菜';
            $this->outputMsg();
        }
        $member = session('member');
        if (empty($member)) {
            $this->_code = 10402;
            $this->_msg = '获取用户信息失败，请稍后重试';
            $this->outputMsg();
        }
        $goods = M('OrderGoods')->field('id, goods_name, goods_image')->where(['id' => $commentId, 'member_id' => $member['member_id']])->find();
        if (empty($goods)) {
            $this->_code = 10301;
            $this->_msg = '无效的信息';
            $this->outputMsg();
        }
        $next = M('OrderGoods')->field('id, goods_name, goods_image')->where("id > {$commentId} AND member_id = {$member['member_id']}")->order('id ASC')->find();
        $this->_code = 0;
        $this->_msg = 'ok';
        $this->_data = ['goods' => $goods, 'next' => $next ? $next : (object)array()];
        $this->outputMsg();
    }

    public function submitComment()
    {
        $commentId = I('post.comment_id');
        $comment = I('post.comment');
        $star = I('post.star');
        if (empty($commentId)) {
            $this->_code = 10300;
            $this->_msg = '请指定评价的菜';
            $this->outputMsg();
        }
        if (empty($comment)) {
            $this->_code = 10301;
            $this->_msg = '请输入评价内容';
            $this->outputMsg();
        }
        if (empty($star)) {
            $this->_code = 10302;
            $this->_msg = '请选择评价星级';
            $this->outputMsg();
        }
        $member = session('member');
        if (empty($member)) {
            $this->_code = 10402;
            $this->_msg = '获取用户信息失败，请稍后重试';
            $this->outputMsg();
        }
        $reuslt = M('OrderGoods')->where(['id' => $commentId, 'member_id' => $member['member_id']])->save(['comment_star' => $star, 'comment' => $comment]);
        if ($reuslt) {
            $this->_code = 0;
            $this->_msg = 'ok';
        } else {
            $this->_code = 10303;
            $this->_msg = '评价失败';
        }
        $this->outputMsg();
    }

    public function getGoodsDetail()
    {
        $goodsId = I('get.goods_id');
        $goods = getGoods($goodsId, false);
        if (empty($goods)) {
            $this->_code = 10211;
            $this->_msg = '错误的菜品';
            $this->outputMsg();
        }
        $this->_code = 0;
        $this->_msg = 'ok';
        $this->_data = $goods;
        $this->outputMsg();
    }

    public function finish()
    {
        $member = session('member');
        if (empty($member)) {
            redirect('/wechat/shop/index');
        }
        $order = S(C('CACHE_KEY_MEMBER_ORDER') . $member['member_id']);
        if (empty($order)) {
            redirect('/wechat/shop/index');
        }
        S(C('CACHE_KEY_MEMBER_ORDER') . $member['member_id'], null);

        $inviteCoupon = getConfig('invite_coupon');
        $coupon = [];
        if ($inviteCoupon) {
            $couponID = getConfig('invite_coupon_id');
            $coupon = M('Coupon')->where(array('status' => 1, 'coupon_id' => $couponID))->find();
        }

        $jsSdk = new JSSDK(C('WECHAT_APPID'), C('WECHAT_APPSECRET'));
        $signPackage = $jsSdk->GetSignPackage();

        if (empty($coupon)) {
            $share = [
                'title' => "熊猫食堂 买手制白领午餐",
                'desc' => "不用选择 才是最好的选择",
                'logo' => C('SITE_URL') . 'shop/images/b100.png',
                'url' => C('SITE_URL') . 'wechat/shop/index?auth=' . encrypt($member['member_id']),
            ];
        } else {
            $share = [
                'title' => "送你{$coupon['coupon_value']}元熊猫食堂美食礼券",
                'desc' => "熊猫食堂 买手制午餐 不用选择 才是最好的选择",
                'logo' => C('SITE_URL') . 'shop/images/b100.png',
                'url' => C('SITE_URL') . 'wechat/shop/invite?auth=' . encrypt($member['member_id']),
            ];
        }
        $first = !empty($member['first']) ? 1 : 0;
        $this->assign('first', $first);
        $this->assign('signPackage', $signPackage);
        $this->assign('coupon', $coupon);
        $this->assign('share', $share);
        $this->display();
    }

    public function invite()
    {
        $memberId = I('get.auth');
        $memberId = decrypt($memberId);

        if (empty($memberId)) {
            exit('网络连接错误，请稍后重试。');
        }

        $auth = new WechatAuth(C('WECHAT_APPID'), C('WECHAT_APPSECRET'));
        if (!isset($_GET['code'])) {
            $baseUrl = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
            $url = $auth->getRequestCodeURL($baseUrl, 'shop', 'snsapi_userinfo');
            Header("Location: {$url}");
            exit();
        } else {
            $token = $auth->getAccessToken('code', $_GET['code']);
        }
        $userInfo = $auth->getUserInfo($token['openid']);
        $member = getMember($token['openid'], false);

        if (empty($member)) {
            $member = array();
            $member['nickname'] = isset($userInfo['nickname']) ? $userInfo['nickname'] : '';
            $member['gender'] = isset($userInfo['sex']) ? $userInfo['sex'] : 0;
            $member['avatar'] = isset($userInfo['headimgurl']) ? $userInfo['headimgurl'] : '';
            $member['openid'] = $userInfo['openid'];
            $member['status'] = 1;
            $member['vip_start_time'] = '0000-00-00';
            $member['vip_end_time'] = '0000-00-00';
            $member['subscribe_time'] = 0;
            $member['create_time'] = NOW_TIME;
            $member['member_id'] = D('Member')->update($member);
            if (!$member['member_id']) {
                exit('网络连接错误，请稍后重试。');
            }
        } else {
            D('Member')->updateMember($member['member_id'], $userInfo['nickname'], $userInfo['sex'], $userInfo['headimgurl']);
        }

        session('member', array('member_id' => $member['member_id'], 'openid' => $member['openid'], 'nickname' => $member['nickname']));

        $auth = M('Member')->where('member_id = ' . $memberId)->find();
        if (empty($auth)) {
            exit('网络连接错误，请稍后重试。');
        }
        $inviteCoupon = getConfig('invite_coupon');
        $coupon = [];
        if ($inviteCoupon) {
            $couponID = getConfig('invite_coupon_id');
            $coupon = M('Coupon')->where(array('status' => 1, 'coupon_id' => $couponID))->find();
        }
        if (empty($coupon)) {
            exit('活动已经结束。');
        }

        if ($memberId != $member['member_id']) {
            $result = M('MemberInvite')->where(['invite_member_id' => $member['member_id']])->find();
            if (empty($result)) {
                M('MemberInvite')->add([
                    'member_id' => $auth['member_id'],
                    'invite_member_id' => $member['member_id'],
                    'coupon_id' => $coupon['coupon_id'],
                    'create_time' => NOW_TIME
                ]);
            }
        }

        $this->assign('coupon', $coupon);
        $this->assign('auth', $auth);
        $this->display();

    }

    public function coupon()
    {
        $auth = new WechatAuth(C('WECHAT_APPID'), C('WECHAT_APPSECRET'));
        if (!isset($_GET['code'])) {
            $baseUrl = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . $_SERVER['QUERY_STRING'];
            $url = $auth->getRequestCodeURL($baseUrl, 'coupon', 'snsapi_base');
            Header("Location: {$url}");
            exit();
        } else {
            $token = $auth->getAccessToken('code', $_GET['code']);
            if (isset($token['errcode'])) {
                $baseUrl = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . $_SERVER['QUERY_STRING'];
                $url = $auth->getRequestCodeURL($baseUrl, 'coupon', 'snsapi_base');
                Header("Location: {$url}");
            }
        }
        $member = getMember($token['openid'], false);
        if (!empty($member)) {
            $coupon = D('MemberCoupon')->getCouponList($member['member_id']);
        } else {
            $coupon = array();
        }
        $this->assign('coupon', $coupon);
        $this->display();
    }

    public function order()
    {
        $auth = new WechatAuth(C('WECHAT_APPID'), C('WECHAT_APPSECRET'));
        if (!isset($_GET['code'])) {
            $baseUrl = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . $_SERVER['QUERY_STRING'];
            $url = $auth->getRequestCodeURL($baseUrl, 'coupon', 'snsapi_base');
            Header("Location: {$url}");
            exit();
        } else {
            $token = $auth->getAccessToken('code', $_GET['code']);
            if (isset($token['errcode'])) {
                $baseUrl = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . $_SERVER['QUERY_STRING'];
                $url = $auth->getRequestCodeURL($baseUrl, 'coupon', 'snsapi_base');
                Header("Location: {$url}");
            }
        }
        $member = getMember($token['openid'], false);

        if (!empty($member)) {
            $unfinishOrderList = array();
            $unfinishOrder = M('OrderGoods')->field('order_id, order_sn, menu_id, goods_name, goods_num')->where(array('member_id' => $member['member_id'], 'order_state' => 2))->select();
            if ($unfinishOrder) {
                foreach ($unfinishOrder as $goods) {
                    $key = $goods['menu_id'] . '_' . $goods['order_id'];
                    $menu = getMenu($goods['menu_id']);
                    $unfinishOrderList[$key]['menu_id'] = $goods['menu_id'];
                    $unfinishOrderList[$key]['menu_date'] = $menu['menu_date'];
                    $unfinishOrderList[$key]['menu_week'] = getWeek($menu['menu_date']);
                    $unfinishOrderList[$key]['order_id'] = $goods['order_id'];
                    $unfinishOrderList[$key]['order_sn'] = $goods['order_sn'];
                    $unfinishOrderList[$key]['goods'][] = ['goods_name' => $goods['goods_name'], 'goods_num' => $goods['goods_num']];
                }
            }

            $finishOrderList = array();
            $finishOrder = M('OrderGoods')->field('id, order_id, order_sn, menu_id, goods_name, goods_num, goods_image, comment_star')->where(array('member_id' => $member['member_id'], 'order_state' => 4))->select();
            if ($finishOrder) {
                foreach ($finishOrder as $goods) {
                    $key = $goods['menu_id'] . '_' . $goods['order_id'];
                    $menu = getMenu($goods['menu_id']);
                    $finishOrderList[$key]['menu_id'] = $goods['menu_id'];
                    $finishOrderList[$key]['menu_date'] = $menu['menu_date'];
                    $finishOrderList[$key]['menu_week'] = getWeek($menu['menu_date']);
                    $finishOrderList[$key]['order_id'] = $goods['order_id'];
                    $finishOrderList[$key]['order_sn'] = $goods['order_sn'];
                    $finishOrderList[$key]['goods'][] = ['id' => $goods['id'], 'goods_name' => $goods['goods_name'], 'goods_num' => $goods['goods_num'], 'comment_star' => $goods['comment_star']];
                }
            }
        } else {
            $finishOrderList = array();
            $unfinishOrderList = array();
        }
        $this->assign('deliverTime', getConfig('deliver_time'));
        $this->assign('finishOrderList', $finishOrderList);
        $this->assign('unfinishOrderList', $unfinishOrderList);
        $this->display();
    }

    public function fail()
    {
        $this->display();
    }

    public function goInvite()
    {
        $auth = new WechatAuth(C('WECHAT_APPID'), C('WECHAT_APPSECRET'));
        if (!isset($_GET['code'])) {
            $baseUrl = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . $_SERVER['QUERY_STRING'];
            $url = $auth->getRequestCodeURL($baseUrl, 'shop', 'snsapi_userinfo');
            Header("Location: {$url}");
            exit();
        } else {
            $token = $auth->getAccessToken('code', $_GET['code']);
        }
        $userInfo = $auth->getUserInfo($token['openid']);
        $member = getMember($token['openid'], false);

        if (empty($member)) {
            redirect("https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=MzAwODM1NzU5NA==&scene=110#wechat_redirect");
        } else {
            D('Member')->updateMember($member['member_id'], $userInfo['nickname'], $userInfo['sex'], $userInfo['headimgurl']);
        }
        $url = C('SITE_URL') . 'wechat/shop/invite?auth=' . encrypt($member['member_id']);
        Header("Location: {$url}");
    }

    public function testWeb()
    {
        $this->display();
    }

    //用户信息
    public function getOpenid()
    {
        if (empty($_GET['code'])) {
            $this->_code = 11001;
            $this->_msg = '微信code为空';
            $this->outputMsg();
        }
        $auth = new WechatAuth(C('WECHAT_APPID'), C('WECHAT_APPSECRET'));
        $token = $auth->getAccessToken('code', $_GET['code']);
        if (isset($token['errcode'])) {
            $baseUrl = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . $_SERVER['QUERY_STRING'];
            $url = $auth->getRequestCodeURL($baseUrl, 'coupon', 'snsapi_base');
            Header("Location: {$url}");
        }
        if (empty($token['openid'])) {
            $this->_code = 11002;
            $this->_msg = '微信响应失败';
            $this->outputMsg();
        }
        $userInfo = $auth->getUserInfo($token['openid']);
        $member = getMember($token['openid'], false);

        if (empty($member)) {
            $member = array();
            $member['nickname'] = isset($userInfo['nickname']) ? $userInfo['nickname'] : '';
            $member['gender'] = isset($userInfo['sex']) ? $userInfo['sex'] : 0;
            $member['avatar'] = isset($userInfo['headimgurl']) ? $userInfo['headimgurl'] : '';
            $member['openid'] = $userInfo['openid'];
            $member['status'] = 1;
            $member['vip_start_time'] = '0000-00-00';
            $member['vip_end_time'] = '0000-00-00';
            $member['subscribe_time'] = 0;
            $member['create_time'] = NOW_TIME;
            $member['member_id'] = D('Member')->update($member);
            if (!$member['member_id']) {
                $this->_code = 10402;
                $this->_msg = '获取用户信息失败，请稍后重试';
                $this->outputMsg();
            }
        } else {
            D('Member')->updateMember($member['member_id'], $userInfo['nickname'], $userInfo['sex'], $userInfo['headimgurl']);
        }
        session('member', array('member_id' => $member['member_id'], 'openid' => $member['openid'], 'nickname' => $member['nickname']));
        $this->_code = 0;
        $this->_msg = 'ok';
        $this->_data = [
            'member_id' => $member['member_id'],
            'openid' => $member['openid'],
            'nickname' => $member['nickname'],
            'avatar' => $member['avatar'],
        ];
        $this->outputMsg();
    }

    //获取用户游戏信息次数
    function getUserGameInfo()
    {
        $member = session('member');
        if (empty($member)) {
            $this->_code = 10402;
            $this->_msg = '获取用户信息失败，请稍后重试';
            $this->outputMsg();
        }
        $openId = I('post.openid');
        if ($member['openid'] != $openId) {
            $this->_code = 10403;
            $this->_msg = '获取用户信息失败，请稍后重试';
            $this->outputMsg();
        }
        $activity = M('MemberActivity')->field('id,member_id,act_count,act_total,is_share')->where(['member_id' => $member['member_id']])->find();
        if (empty($activity)) {
            $activity = array();
            $activity['member_id'] = $member['member_id'];
            $activity['act_total'] = 3;
            $activity['create_time'] = NOW_TIME;
            $result = D('MemberActivity')->update($activity);
        } else {
            if ($activity['act_count'] == $activity['act_total']) {
                $this->_code = 11402;
                $this->_msg = '没有足够的资格';
                $this->outputMsg();
            }
            $activity['act_count'] = $activity['act_count'] + 1;
            $activity['update_time'] = NOW_TIME;
            $result = D('MemberActivity')->update($activity);
        }

        if ($result == false) {
            $this->_code = 11401;
            $this->_msg = '参与失败，请稍后重试';
            $this->outputMsg();
        }

        $this->_code = 0;
        $this->_msg = 'ok';
        $this->_data = ['act_count' => $activity['act_count'], 'act_total' => $activity['act_total'], 'is_share' => $activity['is_share']];
        $this->outputMsg();
    }

    // 分享后 参与次数加1
    function activityShare()
    {
        $member = session('member');
        if (empty($member)) {
            $this->_code = 10402;
            $this->_msg = '获取用户信息失败，请稍后重试';
            $this->outputMsg();
        }
        $openId = I('post.openid');
        if ($member['openid'] != $openId) {
            $this->_code = 10403;
            $this->_msg = '获取用户信息失败，请稍后重试';
            $this->outputMsg();
        }

        $activity = M('MemberActivity')->field('id,member_id,act_count,act_total,is_share')->where(['member_id' => $member['member_id']])->find();
        if (empty($activity)) {
            $this->_code = 11403;
            $this->_msg = '参与失败，请稍后重试';
            $this->outputMsg();
        }

        if ($activity['is_share'] != 1) {
            $activity['act_total'] = $activity['act_total'] + 1;
            $activity['is_share'] = 1;
            $activity['update_time'] = NOW_TIME;
            $result = D('MemberActivity')->update($activity);
            if ($result == false) {
                $this->_code = 11406;
                $this->_msg = '提交失败，请稍后重试';
                $this->outputMsg();
            }
        }

        $this->_code = 0;
        $this->_msg = 'ok';
        $this->_data = ['act_count' => $activity['act_count'], 'act_total' => $activity['act_total'], 'is_share' => $activity['is_share']];
        $this->outputMsg();
    }

    // 获取分享jdk
    function getShareData(){
        $jsSdk = new JSSDK(C('WECHAT_APPID'), C('WECHAT_APPSECRET'));
        $signPackage = $jsSdk->GetSignPackage();
        $share = [
            'title' => "测试分享标题",
            'desc' => "测试分享标题描述",
            'logo' => 'http://wechat.roromy.com/shop/images/b100.png',
            'url' => 'http://wechat.roromy.com',
        ];

        $this->_code = 0;
        $this->_msg = 'ok';
        $this->_data = ['sign' => $signPackage, 'share' => $share];
        $this->outputMsg();
    }

    // 完成后提交。其实这里 把游戏结果上传上来 由服务器端来计算是否完成
    function submitGameData(){
        $openId = I('post.openid');
        $memberName = I('post.member_name');
        $memberPhone = I('post.member_phone');
        $address = I('post.address');

        $member = session('member');
        if (empty($member)) {
            $this->_code = 10402;
            $this->_msg = '获取用户信息失败，请稍后重试';
            $this->outputMsg();
        }

        if ($member['openid'] != $openId) {
            $this->_code = 10403;
            $this->_msg = '获取用户信息失败，请稍后重试';
            $this->outputMsg();
        }

        $activity = M('MemberActivity')->field('id,member_id,act_count,act_total,is_share')->where(['member_id' => $member['member_id']])->find();
        if (empty($activity)) {
            $this->_code = 11403;
            $this->_msg = '参与失败，请稍后重试';
            $this->outputMsg();
        }
        $activity['member_name'] = $memberName;
        $activity['member_phone'] = $memberPhone;
        $activity['address'] = $address;
        $activity['is_finish'] = 1;
        $activity['update_time'] = NOW_TIME;
        $result = D('MemberActivity')->update($activity);
        if ($result == false){
            $this->_code = 11405;
            $this->_msg = '提交失败，请稍后重试';
            $this->outputMsg();
        } else {
            $this->_code = 0;
            $this->_msg = 'ok';
            $this->outputMsg();
        }

    }
}
